package com.fjb.tool.bio.block;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @Description:bio 阻塞客户端 
 * @author hemiao
 * @time:2020年4月14日 下午10:40:03
 */
public class BIoSingleClient {
	
	public static final String QUIT = "quit";
	
	public static void main(String[] args) {
		String host = "127.0.0.1";
		int port = 8089;
		Socket socket = null;
		try {
			socket = new Socket(host, port);	
			System.out.println(" socket 启动成功  host = "+host +" port ="+ port);
			int port2 = socket.getPort();
			// 创建io流
			InputStream inputStream = socket.getInputStream();
			OutputStream outputStream = socket.getOutputStream();
			
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
			
			BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
			
			// 等待用户输入信息
			BufferedReader consoleBufferedReader = new BufferedReader(new InputStreamReader(System.in));
			
			// 获得用户输入的信息
			while (true) {
				String consoleReadLine = consoleBufferedReader.readLine();
				// 发送消息给服务器
				bufferedWriter.write(consoleReadLine+"\n");
				bufferedWriter.flush();
				
				// 读取服务器返回的消息
				String readLine = bufferedReader.readLine();	
				System.out.println(" socket 收到服务端  port2 "+port2+"消息   = " +readLine.toString());
						
				String quit = QUIT;
				if(consoleBufferedReader.toString().equals(quit)) {
					System.out.println(" 客户端退出 ");
					break;	
				}
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(socket!=null) {
				try {
					socket.close();
					System.out.println(" 关闭客户端 socket ");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
}
